package cn.com.geovis.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.com.geovis.demo.enums.EnumCode;
import cn.com.geovis.demo.exception.MyException;
import cn.com.geovis.demo.mapper.DbSourceMapper;
import cn.com.geovis.demo.model.DbSource;
import cn.com.geovis.demo.service.DbSourceService;
import cn.com.geovis.demo.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class DbSourceServiceImpl extends ServiceImpl<DbSourceMapper, DbSource> implements DbSourceService {

  @Override
  public List<DbSource> selectDbSource(DbSource dbSource) {
    List<DbSource> list = super.baseMapper.findDbSource(dbSource);
    System.out.println("---------------------");
    System.out.println(list);
    System.out.println("---------------------");
    return list;
  }

  @Override
  public Object addDbSource(DbSource dbSource) {
    Integer count = super.baseMapper.insert(dbSource);
    if (count == 1) {
      return ResultUtil.result(EnumCode.OK.getValue().toString(), "添加数据源成功");
    }
    throw new MyException(ResultUtil.result(EnumCode.INTERNAL_SERVER_ERROR.getValue().toString(), "新增数据源失败"));
  }

  @Override
  public Object deleteDbSource(Integer[] ids) {
    if (ids == null || ids.length == 0) {
      throw new MyException(ResultUtil.result(EnumCode.BAD_REQUEST.getValue().toString(), EnumCode.BAD_REQUEST.getText()));
    }
    int count = 0;
    for (Integer i : ids) {
      if(i != null)
        count += super.baseMapper.deleteById(i);
    }
    if (count == 0) {
      throw new MyException(ResultUtil.result(EnumCode.GONE.getValue().toString(), "该数据源不存在"));
    } else if (count < ids.length) {
      throw new MyException(ResultUtil.result(EnumCode.INTERNAL_SERVER_ERROR.getValue().toString(), "部分数据源删除失败"));
    }

    return ResultUtil.result(EnumCode.OK.getValue().toString(), "删除成功");
  }

  @Override
  public Object updateDbSource(DbSource dbSource) {
    if (dbSource.getDsId() == null || dbSource.getDsId() <= 0) {
      throw new MyException(ResultUtil.result(EnumCode.BAD_REQUEST.getValue().toString(), "id不合法"));
    }
    int count = super.baseMapper.updateById(dbSource);
    if (count == 1) {
      return ResultUtil.result(EnumCode.OK.getValue().toString(), "数据源更新成功");
    }
    throw new MyException(ResultUtil.result(EnumCode.INTERNAL_SERVER_ERROR.getValue().toString(), "数据源不存在, 更新失败"));
  }
}
